package com.lsj.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lsj.entity.RespBean;
import com.lsj.filter.LoginFilter;
import com.lsj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.*;
import org.springframework.security.web.session.ConcurrentSessionFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;


/*前后端分离项目的会话并发demo*/
@Configuration
public class AnotherSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String contentType = "application/json;charset=utf-8";

    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Autowired
    UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/webjars/**");
    }

    @Bean
    SessionRegistry sessionRegistryImpl(){
        SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
        return sessionRegistry;
    }

    @Bean
    SessionAuthenticationStrategy concurrentSessionControlAuthenticationStrategy(){
        ConcurrentSessionControlAuthenticationStrategy sessionControlAuthenticationStrategy
                = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistryImpl());
        sessionControlAuthenticationStrategy.setMaximumSessions(1);//设置最大会话并发量
        sessionControlAuthenticationStrategy.setExceptionIfMaximumExceeded(true);//如果进行了该设置，当达到最大会话并发量时，禁止后续的用户继续登录
        return sessionControlAuthenticationStrategy;
    }



    @Bean
    SessionAuthenticationStrategy registerSessionAuthenticationStrategy(){
        RegisterSessionAuthenticationStrategy registerSessionAuthenticationStrategy = new RegisterSessionAuthenticationStrategy(sessionRegistryImpl());
        return registerSessionAuthenticationStrategy;
    }


    /*该类的作用是组合其他sessionStrategy策略，然后通过轮询的方式来调用每个sessionStrategy
    * 正常使用的情况下，也是通过该类来维护其他的sessionStrategy实现类*/
    @Bean
    SessionAuthenticationStrategy sessionAuthenticationStrategy(){
        List<SessionAuthenticationStrategy> strategies = new ArrayList<>();
        strategies.add(concurrentSessionControlAuthenticationStrategy());
        strategies.add(registerSessionAuthenticationStrategy());
        CompositeSessionAuthenticationStrategy compositeSessionAuthenticationStrategy = new CompositeSessionAuthenticationStrategy(strategies);
        return compositeSessionAuthenticationStrategy;
    }


    @Bean
    LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setAuthenticationManager(authenticationManager());
        loginFilter.setAuthenticationSuccessHandler((request, response, authentication) -> {
            response.setContentType(contentType);
            PrintWriter writer = response.getWriter();
            RespBean respBean = RespBean.ok("登录成功", authentication);
            ObjectMapper om = new ObjectMapper();
            String result = om.writeValueAsString(respBean);
            writer.write(result);
            writer.flush();
            writer.close();
        });
        loginFilter.setAuthenticationFailureHandler((request, response, exception) -> {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            RespBean respBean = RespBean.error(exception.getMessage());
            if (exception instanceof LockedException) {
                respBean.setMsg("账户被锁定，请联系管理员!");
            } else if (exception instanceof CredentialsExpiredException) {
                respBean.setMsg("密码过期，请联系管理员!");
            } else if (exception instanceof AccountExpiredException) {
                respBean.setMsg("账户过期，请联系管理员!");
            } else if (exception instanceof DisabledException) {
                respBean.setMsg("账户被禁用，请联系管理员!");
            } else if (exception instanceof BadCredentialsException) {
                respBean.setMsg("用户名或者密码输入错误，请重新输入!");
            }else if(exception instanceof SessionAuthenticationException){
                respBean.setMsg("该用户的会话连接数量已达上限，登录操作失败！");
            }
            ObjectMapper om = new ObjectMapper();
            String result = om.writeValueAsString(respBean);
            writer.write(result);
            writer.flush();
            writer.close();
        });
        loginFilter.setFilterProcessesUrl("/doLogin");
        loginFilter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
        return loginFilter;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);//将自定义的登录过滤器添加进去
        http.addFilterAt(new ConcurrentSessionFilter(sessionRegistryImpl(),event -> {
            HttpServletResponse resp = event.getResponse();
            resp.setContentType(contentType);
            resp.setStatus(401);
            PrintWriter out = resp.getWriter();
            out.write(new ObjectMapper().writeValueAsString(RespBean.error("您已在另一台设备登录，本次登录已下线!")));
            out.flush();
            out.close();
        }),ConcurrentSessionFilter.class);
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login2.html")
                .permitAll()
                .and()
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        response.setContentType(contentType);
                        PrintWriter writer = response.getWriter();
                        RespBean respBean = RespBean.error("访问失败,请先登录！");
                        ObjectMapper om = new ObjectMapper();
                        String result = om.writeValueAsString(respBean);
                        writer.write(result);
                        writer.flush();
                        writer.close();
                    }
                });
    }
}
